from odoo import fields, models, api
from odoo.exceptions import UserError, ValidationError

from ...functions.common import check_intersection_with_details
from ...functions.operation_control_fc import OperationControlFC


class RPCourierCostTemplate(models.Model):
    _name = "rp.courier.cost.template"
    _description = '承运商成本价'
    _rec_name = 'name'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _sql_constraints = [('unique_name', 'UNIQUE(name)', '名称不允许重复')]

    name = fields.Char(string='名称', required=True, copy=False, index=True, tracking=True)
    code = fields.Char(string='编码', readonly=True, default='RP_CCT/***', copy=False, index=True, tracking=True)
    courier_id = fields.Many2one(string='承运商', required=True, comodel_name='rp.courier', tracking=True)

    operation_display = fields.Char(string='头尾程', default='-,-,-,-', compute='_depends_fulfill_operation', store=True, tracking=True)
    operation_dropoff = fields.Boolean(string='网点收件', related='courier_id.operation_dropoff', readonly=True)
    operation_pickup = fields.Boolean(string='上门取件', related='courier_id.operation_pickup', readonly=True)
    operation_collect = fields.Boolean(string='网点取件', related='courier_id.operation_collect', readonly=True)
    operation_delivery = fields.Boolean(string='送货上门', related='courier_id.operation_delivery', readonly=True)

    value_added_ids = fields.Many2many(string='增值服务', comodel_name='rp.value.added.service', related='courier_id.value_added_ids',
                                       relation='rp_courier_cost_and_value_added_rel', column1='courier_cost_id', column2='value_added_id')

    desc = fields.Text(string='描述', tracking=True)
    remarks = fields.Text(string='备注', tracking=True)

    rp_courier_cost_template_mail_route_line_ids = fields.One2many(string='关联邮路明细', comodel_name='rp.courier.cost.template.mail.route.line', inverse_name='rp_courier_cost_template_id')
    rp_courier_cost_template_value_added_line_ids = fields.One2many(string='关联增值明细', comodel_name='rp.courier.cost.template.value.added.line', inverse_name='rp_courier_cost_template_id')

    mail_route_rule_flag = fields.Boolean(string='邮路规则', default=True, compute='_depends_compute_mail_route_rule', store=True)
    value_added_rule_flag = fields.Boolean(string='增值服务规则', default=True, compute='_depends_compute_value_added_rule', store=True)
    active_flag = fields.Boolean(string='有效', default=False, readonly=True, store=True)

    @api.onchange('courier_id')
    def _onchange_fulfill_courier_info(self):
        if self.courier_id:
            self.rp_courier_cost_template_value_added_line_ids = [(5, 0)]
            value_added = self.env['rp.value.added.service'].search([('name', 'in', [i.name for i in self.value_added_ids])])
            self.update({'rp_courier_cost_template_value_added_line_ids': [(0, 0, {'courier_value_added_id': i.id}) for i in value_added]})

    @api.depends('operation_pickup', 'operation_dropoff', 'operation_delivery', 'operation_collect')
    def _depends_fulfill_operation(self):
        for s in self:
            operation = OperationControlFC(self.env, s.operation_dropoff, s.operation_pickup, s.operation_collect, s.operation_delivery)
            s.write({'operation_display': operation.fulfill_display()})

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['code'] = self.env['ir.sequence'].sudo().next_by_code('rp.courier.cost.template') or '/'
        return super(RPCourierCostTemplate, self).create(vals_list)

    @api.depends('rp_courier_cost_template_mail_route_line_ids.aging_id',
                 'rp_courier_cost_template_mail_route_line_ids.courier_mail_route_id',
                 'rp_courier_cost_template_mail_route_line_ids.ship_from_country_group_ids',
                 'rp_courier_cost_template_mail_route_line_ids.ship_to_country_group_ids')
    def _depends_compute_mail_route_rule(self):
        """ 计算模板规则 """
        for s in self:
            if s.rp_courier_cost_template_mail_route_line_ids:
                mail_route_list = []
                for mrl in s.rp_courier_cost_template_mail_route_line_ids:
                    if all([mrl.aging_id, mrl.courier_mail_route_id, mrl.ship_from_country_group_ids, mrl.ship_to_country_group_ids]):
                        mail_route_list.append((mrl.aging_id, mrl.courier_mail_route_id.id, mrl.ship_from_country_group_ids.ids, mrl.ship_to_country_group_ids.ids))
                check_dict = check_intersection_with_details(mail_route_list)
                if check_dict['has_intersection']:
                    cost_mail_routes = self.env['rp.courier.cost.template.mail.route.line'].browse()
                    for key in check_dict['intersections']:
                        value = check_dict['intersections'][key].pop()
                        cost_mail_route = s.rp_courier_cost_template_mail_route_line_ids.filtered(lambda i: all([i.aging_id.id == key[0].id,
                                                                                                                 i.courier_mail_route_id.id == key[1],
                                                                                                                 set(i.ship_from_country_group_ids.ids) & set([value[0]]),
                                                                                                                 set(i.ship_to_country_group_ids.ids) & set([value[1]])]))
                        cost_mail_routes = cost_mail_routes | cost_mail_route
                    raise UserError('同一个时效，同一个邮路，不允许存在相同路径。以下是存在重复的成本价邮路code:' + str([cmr.code for cmr in cost_mail_routes]))
                s.write({'mail_route_rule_flag': check_dict['has_intersection']})

    @api.depends('rp_courier_cost_template_value_added_line_ids.courier_value_added_id')
    def _depends_compute_value_added_rule(self):
        for s in self:
            if s.rp_courier_cost_template_value_added_line_ids:
                value_added_list = []
                for val in s.rp_courier_cost_template_value_added_line_ids:
                    if val.courier_value_added_id:
                        value_added_list.append(val.courier_value_added_id.id)
                if len(value_added_list) != len(list(set(value_added_list))):
                    raise UserError('同一个承运商，同一个增值服务，不能设置多个成本价。（不同成本价模板不受影响）')
                s.write({'value_added_rule_flag': True})
